import json

from django import http
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU
from meiduo_mall.settings.dev import logger
from utils.cookiesecret import CookieSecret






from utils.response_code import RETCODE

#1.添加,查询购物车
class CartsView(View):
    #添加
    def post(self, request):
        #接收数据
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        #校验数据
        if not all([sku_id, count, selected]):
            return http.HttpResponseForbidden('缺少必传参数')

        try:
            SKU.objects.get(id = sku_id)
        except Exception as e:
            logger.error(e)
            return http.HttpResponseForbidden("商品不存在")

        try:
            count = int(count)
        except Exception as e:
            logger.error(e)
            return http.HttpResponseForbidden('参数count有误')

        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        #判断是否登录
        user = request.user
        # 登录 redis
        if user.is_authenticated:
            #连接数据库
            redis_client = get_redis_connection('carts')
            #获取登录用户的购物车数据
            client_data = redis_client.hgetall(user.id)
            #判断是否有该用户的记录
            if not client_data:
                redis_client.hset(user.id, sku_id, json.dumps({'count':count, 'selected':selected}))

            #有记录count+=1

            #判断加入的商品  是否加入   加入count+=1  未加入添加  并修改数据
            if str(sku_id).encode() in client_data:
                sku_dict = json.loads(client_data[str(sku_id).encode()].decode())
                sku_dict['count'] += count
                redis_client.hset(user.id, sku_id, json.dumps(sku_dict))
            else:
                redis_client.hset(user.id, sku_id, json.dumps({'count':count, 'selected':selected}))

            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})

        #未登录 cookie
        else:
            # 1.取出数据
            carts_str = request.COOKIES.get('carts')
            # 2.判断是否存在 存在 解密增  不存在建
            if carts_str:
                carts_dict = CookieSecret.loads(carts_str)
            else:
                carts_dict = {}
            # 3.判断商品是否存在  存在 增  不存在建
            if sku_id in carts_dict:
                origin_count = carts_dict[sku_id]['count']
                count = origin_count + count

            carts_dict[sku_id] = {
                'count':count,
                'selected':selected
            }

            cookie_secret = CookieSecret.dumps(carts_dict)
            # 4.添加cookie
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
            response.set_cookie('carts', cookie_secret, max_age=14*24*3600)
            return response


    #查询
    def get(self, request):
        user = request.user
        #判断是否登录
        if user.is_authenticated:
            redis_client = get_redis_connection('carts')
            client_data = redis_client.hgetall(user.id)
            cart_dict = {int(sku_id.decode()): json.loads(dict_data.decode()) for sku_id, dict_data in client_data.items()}

        else:
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}
            #需要返回的数据 id, name, default_image_url, price, count , selectde
        sku_ids = cart_dict.keys()
        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id = sku_id)
            skus.append({
                'id':sku.id,
                'name':sku.name,
                'default_image_url':sku.default_image.url,
                'price':str(sku.price),
                'count':cart_dict[sku_id]['count'],
                'selected': str(cart_dict[sku_id]['selected']),
                'amount':str(sku.price*cart_dict[sku_id]['selected'])
            })

        context = {
            'cart_skus':skus
        }

        return render(request, 'cart.html', context)


    #修改
    def put(self,request):
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)
        # 判断参数是否齐全
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断sku_id是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品sku_id不存在')
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('参数count有误')
        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')
        user = request.user
        cart_secret = ''
        if user.is_authenticated:
            redis_client = get_redis_connection('carts')
            redis_dict = {'count':count, 'selected':selected}
            redis_client.hset(user.id, sku_id, json.dumps(redis_dict))

        else:
            cart_str = request.COOKIES.get('caers')
            if cart_str:
                cart_dict = CookieSecret.loads(cart_str)

            else:
                cart_dict = {}

            cart_dict[sku_id] = {'count':count, 'selected':selected}
            cart_secret = CookieSecret.dumps(cart_dict)

        cart_sku = {
            'id': sku_id,
            'count': count,
            'selected': selected,
            'name': sku.name,
            'default_image_url': sku.default_image.url,
            'price': sku.price,
            'amount': sku.price * count
        }
        response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
        if not user.is_authenticated:
            response.set_cookie('carts', cart_secret, max_age=14*24*3600)

        return response

    #删除
    def delete(self,request):
        sku_id = json.loads(request.body.decode()).get('sku_id')

        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            logger.error(e)
            return  http.HttpResponseForbidden('商品不存在')

        user = request.user
        cart_secret = ''
        if user.is_authenticated:
            redis_client = get_redis_connection('carts')
            redis_client.hdel(user.id, sku_id)
        else:
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}
            if sku_id in cart_dict:
                del cart_dict[sku_id]
            cart_secret = CookieSecret.dumps(cart_dict)

        response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})

        if not user.is_authenticated:
            response.set_cookie('carts', cart_secret, max_age=14*24*3600)

        return response


#2.全选购物车
class CartsSelectAllView(View):
    def put(self, request):
        selected = json.loads(request.body.decode()).get('selected', True)

        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('selected类型不对')

        user = request.user
        cart_secret = ''
        if user.is_authenticated:
            redis_client = get_redis_connection('carts')
            redis_data = redis_client.hgetall(user.id)
            for data in redis_data.items():
                sku_id = int(data[0].decode())
                sku_dict = json.loads(data[1].decode())
                sku_dict['selected'] = selected
                redis_client.hset(user.id, sku_id, json.dumps(sku_dict))

        else:
            cart_str = request.COOKIES.get('carts')
            if cart_str is not None:
                cart_dict = CookieSecret.loads(cart_str)
                for sku_id in cart_dict:
                    cart_dict[sku_id]['selected'] = selected
                cart_secret = CookieSecret.dumps(cart_dict)
        response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})
        if not user.is_authenticated:
            response.set_cookie('carts', cart_secret, max_age=14*24*3600)

        return response


#3.购物车简单展示
class CartsSimpleView(View):
    def get(self, request):
        user = request.user
        #redis
        if user.is_authenticated:
            redis_client = get_redis_connection('carts')
            cart_redis = redis_client.hgetall(user.id)
            cart_dict = {int(sku_id.decode()):json.loads(dict_data.decode()) for sku_id, dict_data in cart_redis.items()}

        # cookie
        else:
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = CookieSecret.loads(cart_str)

            else:
                cart_dict = {}

        cart_skus = []
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in = sku_ids)
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'default_image_url': sku.default_image.url
            })

        return http.JsonResponse({'code':RETCODE.OK, 'errmsg':'OK', 'cart_skus':cart_skus})


